package com.tarena.sentinel.demo01.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.tarena.sentinel.demo01.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @Autowired
    private HelloService helloService;
    @GetMapping("/hello")
    public String sayHi(String name){
        //sentinel 每定义一个资源,要设置一个entry入口对象,资源的访问
        //经过入口对象,没有违反规则正常访问,如果违反了规则,入口对象赋值过程就会抛出拦截异常
        Entry entry=null;
        //resource01就是我们定义的资源名称
        String result=null;
        try {
            entry = SphU.entry("resource01");
            result=helloService.sayHi(name);
        }catch (BlockException e){
            //如果抛出异常,证明本次请求 超出了流量控制上限
            //可以在catch中编写降级的逻辑
            return "你的请求被流量拦截了";
        }finally {
            //释放赋值的资源
            if (entry!=null)entry.exit();
        }
        return result;
    }
    @GetMapping("/sayBye")
    public String sayBye() throws BlockException {
        Entry entry=SphU.entry("resource03");
        helloService.sayHi("nihao ");
        return "bye bye";
    }
}
